/**
 * @NModuleScope Public
 * @NApiVersion 2.x
 */
define(['N/record', 'N/search', 'N/runtime', '../common/txUtil'], function (record, search, runtime, txUtil) {
    var marketplaceId, currency, country;

    function handleReport(param) {
        log.audit("开始  剩余限制:", runtime.getCurrentScript().getRemainingUsage());
        var startTime = new Date().getTime();

        var reportId = param.reportId;
        var reports = param.reports;


        var reportRecordTypeId = getReportRecordTypeId(param.reportType);
        var reportPrefixName = getReportPrefixName(reportRecordTypeId);

        marketplaceId = getMarketplaceId(reportRecordTypeId, reports);   // 根据报表内容 settlement 和 transaction 的marketplaceId
        currency = getTxCurrency(reportRecordTypeId, reports); // 获得transaction报表的货币

        var language = runtime.getCurrentUser().getPreference('LANGUAGE');

        if (language === "zh_CN") {
            country = getTxCountryCN(reportRecordTypeId, reports);// 获得transaction报表的国家
        } else {
            country = getTxCountryEN(reportRecordTypeId, reports);// 获得transaction报表的国家
        }
        //log.debug('language', language);

        log.debug('marketplaceId', marketplaceId);
        log.debug('currency', currency);
        log.debug('country', country);

        var storeId;
      try{
         storeId= getStoreId(param.sellerId, marketplaceId);
      }catch(e){}
     
        log.debug('storeId', storeId);
        var results = [];

        if (reportRecordTypeId === "customrecord_fba_transaction_report") {
            reports[0].reportData = getTxReportHeader(reports[0].reportData);
        }
        var reportHeader = JSON.parse(reports[0].reportData);

        for (var i = 1; i < reports.length; i++) {
            try {
                var reportContent = JSON.parse(reports[i].reportData);
                var result = {};
                result.reportId = reportId;
                result.lineNumber = reports[i].lineNumber;

                var nsReportId = creteReport(reportRecordTypeId, reportPrefixName, reportHeader, reportContent, storeId);
                result.message = 'push success!ns report id:' + nsReportId;
                result.success = true;
            } catch (e) {
                result.message = 'push error:' + JSON.stringify(e).substring(0, 450);
                result.success = false;
            }
            results[results.length] = result;
        }


        log.audit("结束  剩余限制:", runtime.getCurrentScript().getRemainingUsage());
        var endTime = new Date().getTime();
        log.audit('总共耗时:', (endTime - startTime) / 1000 + '秒');
        return results;
    }

    function creteReport(reportRecordTypeId, reportPrefixName, reportHeader, reportContent, storeId) {
        var nsReportId;
        var rec = record.create({type: reportRecordTypeId});
        rec.setValue(reportPrefixName + 'store_information', storeId);

        if (reportRecordTypeId === "customrecord_fba_transaction_report"){
            rec.setText("custrecord_tran_currency", currency);
            rec.setText("custrecord_tran_country", country);
        }

        for (var i = 0; i < reportHeader.length; i++) {
            var id = reportHeader[i].replace(/-/g, "_").replace(/\s/g, "_").toLowerCase();
            id = reportPrefixName + id;
            id = id.length <= 40 ? id : id.substr(0, 40);
            rec.setValue(id, reportContent[i]);
        }

        nsReportId = rec.save();
        return nsReportId;
    }


    function getMarketplaceId(reportRecordTypeId, reports) {
        var marketplaceId;
        if (reportRecordTypeId === "customrecord_fba_settlement_report") {
            var marketplaceName = JSON.parse(reports[2].reportData)[7];
            switch (marketplaceName.toLowerCase()) {
                case "amazon.com" :
                    marketplaceId = "ATVPDKIKX0DER";
                    break;
                case "amazon.br" :
                    marketplaceId = "A2Q3Y263D00KWC";
                    break;
                case "amazon.ca" :
                    marketplaceId = "A2EUQ1WTGCTBG2";
                    break;
                case "amazon.mx" :
                    marketplaceId = "A1AM78C64UM0Y8";
                    break;
                case "amazon.ae" :
                    marketplaceId = "A2VIGQ35RCS4UG";
                    break;
                case "amazon.de" :
                    marketplaceId = "A1PA6795UKMFR9";
                    break;
                case "amazon.es" :
                    marketplaceId = "A1RKKUPIHCS9HS";
                    break;
                case "amazon.fr" :
                    marketplaceId = "A13V1IB3VIYZZH";
                    break;
                case "amazon.gb" :
                    marketplaceId = "A1F83G8C2ARO7P";
                    break;
                case "amazon.in" :
                    marketplaceId = "A21TJRUUN4KGV";
                    break;
                case "amazon.it" :
                    marketplaceId = "APJ6JRA9NG5V4";
                    break;
                case "amazon.tr" :
                    marketplaceId = "A33AVAJ2PDY3EV";
                    break;
                case "amazon.sg" :
                    marketplaceId = "A19VAU5U5O7RUS";
                    break;
                case "amazon.au" :
                    marketplaceId = "A39IBJ37TRP1C6";
                    break;
                case "amazon.jp" :
                    marketplaceId = "A1VC38T7YXB528";
                    break;
                default :
                    marketplaceId = "ATVPDKIKX0DER";
            }
        }
        if (reportRecordTypeId === "customrecord_fba_transaction_report") {
            var reportHeader = JSON.parse(reports[0].reportData);
            var reportContent = JSON.parse(reports[1].reportData);
            var datetime = reportHeader[0];
            switch (datetime) {
                case "date/time" :
                    if (reportContent[7].toLowerCase() === "amazon.com") {
                        marketplaceId = "ATVPDKIKX0DER"; //US;
                    } else if (reportContent[7].toLowerCase() === "amazon.ca") {
                        marketplaceId = "A2EUQ1WTGCTBG2"; //CA;
                    } else if (reportContent.length === 21) {
                        marketplaceId = "A21TJRUUN4KGV"; //IN;
                    } else if (reportContent.length === 22) {
                        marketplaceId = "A1F83G8C2ARO7P"; //UK;
                    } else {
                        marketplaceId = "ATVPDKIKX0DER"; //US;
                    }
                    break;
                case "日付/時間" :
                    marketplaceId = "A1VC38T7YXB528"; //JP;
                    break;
                case "Datum/Uhrzeit" :
                    marketplaceId = "A1PA6795UKMFR9"; //DE;
                    break;
                case "date/heure" :
                    marketplaceId = "A13V1IB3VIYZZH"; //FR;
                    break;
                case "Data/Ora:" :
                    marketplaceId = "APJ6JRA9NG5V4"; //IT;
                    break;
                case "fecha y hora" :
                    marketplaceId = "A1RKKUPIHCS9HS"; //ES;
                    break;
                case "fecha/hora" :
                    marketplaceId = "A1AM78C64UM0Y8"; //MX;
                    break;
                default :
                    marketplaceId = "ATVPDKIKX0DER"; //US;
                    break;
            }
        }
        return marketplaceId;
    }

    function getTxCountryEN(reportRecordTypeId, reports) {
        var country;
        if (reportRecordTypeId === "customrecord_fba_transaction_report") {
            var reportHeader = JSON.parse(reports[0].reportData);
            var reportContent = JSON.parse(reports[1].reportData);
            var datetime = reportHeader[0];
            switch (datetime) {
                case "date/time" :
                    if (reportContent[7].toLowerCase() === "amazon.com") {
                        country = "United States"; //US;
                    } else if (reportContent[7].toLowerCase() === "amazon.ca") {
                        country = "Canada"; //CA;
                    } else if (reportContent.length === 21) {
                        country = "India"; //IN;
                    } else if (reportContent.length === 22) {
                        country = "United Kingdom"; //UK;
                    } else {
                        country = "United States"; //US;
                    }
                    break;
                case "日付/時間" :
                    country = "Japan"; //JP;
                    break;
                case "Datum/Uhrzeit" :
                    country = "Germany"; //DE;
                    break;
                case "date/heure" :
                    country = "France"; //FR;
                    break;
                case "Data/Ora:" :
                    country = "Italy"; //IT;
                    break;
                case "fecha y hora" :
                    country = "Spain"; //ES;
                    break;
                case "fecha/hora" :
                    country = "Mexico"; //MX;
                    break;
                default :
                    country = "United States"; //US;
                    break;
            }
        }
        return country;
    }

    function getTxCountryCN(reportRecordTypeId, reports) {
        var country;
        if (reportRecordTypeId === "customrecord_fba_transaction_report") {
            var reportHeader = JSON.parse(reports[0].reportData);
            var reportContent = JSON.parse(reports[1].reportData);
            var datetime = reportHeader[0];
            switch (datetime) {
                case "date/time" :
                    if (reportContent[7].toLowerCase() === "amazon.com") {
                        country = "美国"; //US;
                    } else if (reportContent[7].toLowerCase() === "amazon.ca") {
                        country = "加拿大"; //CA;
                    } else if (reportContent.length === 21) {
                        country = "印度"; //IN;
                    } else if (reportContent.length === 22) {
                        country = "英国"; //UK;
                    } else {
                        country = "美国"; //US;
                    }
                    break;
                case "日付/時間" :
                    country = "日本"; //JP;
                    break;
                case "Datum/Uhrzeit" :
                    country = "德国"; //DE;
                    break;
                case "date/heure" :
                    country = "法国"; //FR;
                    break;
                case "Data/Ora:" :
                    country = "意大利"; //IT;
                    break;
                case "fecha y hora" :
                    country = "西班牙"; //ES;
                    break;
                case "fecha/hora" :
                    country = "墨西哥"; //MX;
                    break;
                default :
                    country = "美国"; //US;
                    break;
            }
        }
        return country;
    }

    function getTxCurrency(reportRecordTypeId, reports) {
        var currency;
        if (reportRecordTypeId === "customrecord_fba_transaction_report") {
            var reportHeader = JSON.parse(reports[0].reportData);
            var reportContent = JSON.parse(reports[1].reportData);
            var datetime = reportHeader[0];
            if (datetime === "date/time") {
                if (reportContent[7].toLowerCase() === "amazon.com") {
                    currency = "USD"; //US;
                } else if (reportContent[7].toLowerCase() === "amazon.ca") {
                    currency = "CAD"; //CA;
                } else if (reportContent.length === 21) {
                    // currency = ""; //IN;
                } else if (reportContent.length === 22) {
                    currency = "GBP"; //UK;
                } else {
                    currency = "USD"; //US;
                }
            } else if (datetime === "日付/時間") {
                currency = "JPY"; //JP;
            } else if (datetime === "Datum/Uhrzeit"
                || datetime === "date/heure"
                || datetime === "Data/Ora:"
                || datetime === "fecha y hora") {
                currency = "EUR"; //DE;  //FR; //IT;  //ES;
            } else if (datetime === "fecha/hora") {
                currency = "USD"; //MX;

            } else {
                currency = "USD"; //US;

            }
        }
        return currency;
    }

    function getReportRecordTypeId(reportType) {
        var reportRecordTypeIds = {
            "_GET_AFN_INVENTORY_DATA_": "customrecord_fba_fulfilled_invt_report",
            "_GET_FBA_FULFILLMENT_CUSTOMER_RETURNS_DATA_": "customrecord_fba_returns_report",
            "_GET_FBA_FULFILLMENT_CUSTOMER_SHIPMENT_PROMOTION_DATA_": "customrecord_fba_promotions_report",
            "_GET_FBA_MYI_ALL_INVENTORY_DATA_": "customrecord_fba_invt_manage_report",
            "_GET_FBA_REIMBURSEMENTS_DATA_": "customrecord_fba_reimbursements_report",
            "_GET_FBA_FULFILLMENT_REMOVAL_ORDER_DETAIL_DATA_": "customrecord_fba_rem_order_detail_report",
            "_GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE_V2_": "customrecord_fba_settlement_report",
            "_GET_DATE_RANGE_FINANCIAL_TRANSACTION_DATA_": "customrecord_fba_transaction_report",
            "_GET_FBA_FULFILLMENT_LONGTERM_STORAGE_FEE_CHARGES_DATA_": "customrecord_fba_storage_fee_report",
            "_GET_AMAZON_FULFILLED_SHIPMENTS_DATA_": "customrecord_fba_fulfilled_ship_report",
            "_GET_FBA_FULFILLMENT_INVENTORY_HEALTH_DATA_": "customrecord_fba_invt_health_report",
            "_GET_FBA_FULFILLMENT_CUSTOMER_SHIPMENT_REPLACEMENT_DATA_": "customrecord_fba_replacements_report",
            "_GET_FBA_FULFILLMENT_CURRENT_INVENTORY_DATA_": "customrecord_fba_daily_invt_report",
            "_GET_RESERVED_INVENTORY_DATA_": "customrecord_fba_reserved_invt_report",
            "_GET_FBA_FULFILLMENT_REMOVAL_SHIPMENT_DETAIL_DATA_": "customrecord_fba_rem_ship_detail_report"
        };
        var reportRecordTypeId = reportRecordTypeIds[reportType];
        if (reportRecordTypeId) {
            return reportRecordTypeId;
        } else {
            return null;
        }
    }

    function getReportPrefixName(reportRecordTypeId) {
        var reportPrefixNames = {
            "customrecord_fba_fulfilled_invt_report": "custrecord_invt_",
            "customrecord_fba_returns_report": "custrecord_return_",
            "customrecord_fba_promotions_report": "custrecord_prom_",
            "customrecord_fba_invt_manage_report": "custrecord_mana_invt_",
            "customrecord_fba_reimbursements_report": "custrecord_reim_",
            "customrecord_fba_rem_order_detail_report": "custrecord_rem_order_",
            "customrecord_fba_settlement_report": "custrecord_settle_",
            "customrecord_fba_transaction_report": "custrecord_tran_",
            "customrecord_fba_storage_fee_report": "custrecord_storage_fee_",
            "customrecord_fba_fulfilled_ship_report": "custrecord_ful_ship_",
            "customrecord_fba_invt_health_report": "custrecord_invh_",
            "customrecord_fba_replacements_report": "custrecord_replace_",
            "customrecord_fba_daily_invt_report": "custrecord_d_invt_",
            "customrecord_fba_reserved_invt_report": "custrecord_r_invt_",
            "customrecord_fba_rem_ship_detail_report": "custrecord_rem_ship_"
        };
        var reportPrefixName = reportPrefixNames[reportRecordTypeId];
        if (reportPrefixName) {
            return reportPrefixName;
        } else {
            return null;
        }
    }

    function getTxReportHeader(txReportHeader) {
        return txReportHeader.replace("date/time", "datetime")
            .replace("日付/時間", "datetime")
            .replace("Datum/Uhrzeit", "datetime")
            .replace("date/heure", "datetime")
            .replace("Data/Ora:", "datetime")
            .replace("fecha y hora", "datetime")
            .replace("fecha/hora", "datetime")
            .replace("決済番号", "settlement id")
            .replace("Abrechnungsnummer", "settlement id")
            .replace("numéro de versement", "settlement id")
            .replace("Numero pagamento", "settlement id")
            .replace("identificador de pago", "settlement id")
            .replace("Id. de liquidación", "settlement id")
            .replace("トランザクションの種類", "type")
            .replace("Typ", "type")
            .replace("Tipo", "type")
            .replace("tipo", "type")
            .replace("注文番号", "order id")
            .replace("Bestellnummer", "order id")
            .replace("numéro de la commande", "order id")
            .replace("Numero ordine", "order id")
            .replace("número de pedido", "order id")
            .replace("Id. del pedido", "order id")
            .replace("説明", "description")
            .replace("Beschreibung", "description")
            .replace("Descrizione", "description")
            .replace("descripción", "description")
            .replace("数量", "quantity")
            .replace("Menge", "quantity")
            .replace("quantité", "quantity")
            .replace("Quantità", "quantity")
            .replace("cantidad", "quantity")
            .replace("Amazon 出品サービス", "marketplace")
            .replace("web de Amazon", "marketplace")
            .replace("フルフィルメント", "fulfillment")
            .replace("Versand", "fulfillment")
            .replace("traitement", "fulfillment")
            .replace("Gestione", "fulfillment")
            .replace("gestión logística", "fulfillment")
            .replace("cumplimiento", "fulfillment")
            .replace("市町村", "order city")
            .replace("Ort der Bestellung", "order city")
            .replace("ville d'où provient la commande", "order city")
            .replace("Città di provenienza dell'ordine", "order city")
            .replace("ciudad de procedencia del pedido", "order city")
            .replace("ciudad del pedido", "order city")
            .replace("Bundesland", "order state")
            .replace("Région d'où provient la commande", "order state")
            .replace("Provincia di provenienza dell'ordine", "order state")
            .replace("comunidad autónoma de procedencia del pedido", "order state")
            .replace("estado del pedido", "order state")
            .replace("郵便番号", "order postal")
            .replace("Postleitzahl", "order postal")
            .replace("code postal de la commande", "order postal")
            .replace("CAP dell'ordine", "order postal")
            .replace("código postal de procedencia del pedido", "order postal")
            .replace("código postal del pedido", "order postal")
            .replace("商品売上", "product sales")
            .replace("Umsätze", "product sales")
            .replace("ventes de produits", "product sales")
            .replace("Vendite", "product sales")
            .replace("ventas de productos", "product sales")
            .replace("postage credits", "shipping credits")
            .replace("配送料", "shipping credits")
            .replace("Gutschrift für Versandkosten", "shipping credits")
            .replace("crédits d'expédition", "shipping credits")
            .replace("Accrediti per le spedizioni", "shipping credits")
            .replace("abonos de envío", "shipping credits")
            .replace("créditos de envío", "shipping credits")
            .replace("ギフト包装手数料", "gift wrap credits")
            .replace("Gutschrift für Geschenkverpackung", "gift wrap credits")
            .replace("crédits sur l'emballage cadeau", "gift wrap credits")
            .replace("Accrediti per confezioni regalo", "gift wrap credits")
            .replace("abonos de envoltorio para regalo", "gift wrap credits")
            .replace("Amazonポイントの費用", "promotional rebates")
            .replace("Rabatte aus Werbeaktionen", "promotional rebates")
            .replace("Rabais promotionnels", "promotional rebates")
            .replace("Sconti promozionali", "promotional rebates")
            .replace("devoluciones promocionales", "promotional rebates")
            .replace("descuentos promocionales", "promotional rebates")
            .replace("プロモーション割引額", "sales tax collected")
            .replace("手数料", "selling fees")
            .replace("Verkaufsgebühren", "selling fees")
            .replace("frais de vente", "selling fees")
            .replace("Commissioni di vendita", "selling fees")
            .replace("tarifas de venta", "selling fees")
            .replace("FBA 手数料", "fba fees")
            .replace("Gebühren zu Versand durch Amazon", "fba fees")
            .replace("Frais Expédié par Amazon", "fba fees")
            .replace("Costi del servizio Logistica di Amazon", "fba fees")
            .replace("tarifas de Logística de Amazon", "fba fees")
            .replace("tarifas fba", "fba fees")
            .replace("トランザクションに関するその他の手数料", "other transaction fees")
            .replace("Andere Transaktionsgebühren", "other transaction fees")
            .replace("autres frais de transaction", "other transaction fees")
            .replace("Altri costi relativi alle transazioni", "other transaction fees")
            .replace("tarifas de otras transacciones", "other transaction fees")
            .replace("tarifas de otra transacción", "other transaction fees")
            .replace("その他", "other")
            .replace("Andere", "other")
            .replace("autre", "other")
            .replace("Altro", "other")
            .replace("otro", "other")
            .replace("合計", "total")
            .replace("Gesamt", "total")
            .replace("totale", "total")

    }

    function getStoreId(sellerId, marketplaceId) {
        var storeId;
        var results = search.create({
            type: 'customrecord_platform_marketplace',
            filters: ['custrecord_marketplace_code', 'is', marketplaceId]
        }).run().getRange(0, 1);
        var marketplace = results[0].id;
        log.debug('marketplace', marketplace);

        search.create({
            type: 'customrecord_platform_store_information',
            columns: [],
            filters: [['custrecord_store_seller_id', 'is', sellerId],
                'and', ['custrecord_store_marketplace_id', 'is', marketplace]]
        }).run().each(function (result) {
            storeId = result.id;
        });
        return storeId;
    }

    return {
        handleReport: handleReport
    };
});